package com.example.auth.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

/**
 * sys-user
 * this user will implement UserDetails, so we can use this in Spring Security
 *
 * @author cuihaida
 */
@Data
public class SysUser implements UserDetails {

    /**
     * user id
     */
    private Long id;

    /**
     * user name
     */
    private String username;

    /**
     * user password
     */
    private String password;

    /**
     * user avatar
     */
    private String avatar;

    /**
     * user sex, 1:male, 2:female
     */
    private Integer sex;

    /**
     * user phone number
     */
    private String phone;

    /**
     * user email
     */
    private String email;

    /**
     * user state, 1:normal, 2:locked, 3:deleted, 4:disabled
     */
    private Integer state;

    /**
     * user remark
     */
    private String remark;

    /**
     * user create time
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    private LocalDateTime createTime;

    /**
     * user department id
     */
    private Long deptId;


    /**
     * user have roles, will join with role by user-role table
     * will use it in spring security
     */
    @JsonIgnore
    Collection<? extends GrantedAuthority> authorities;

    /**
     * user menus
     */
    @JsonIgnore
    List<SysMenu> menus;


    /**
     * user account is expired?
     */
    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        return state != null && state != 3;
    }

    /**
     * user account is locked?
     */
    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        return state != null && state != 2;
    }

    /**
     * user credentials is expired?
     */
    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        return state != null && state != 4;
    }

    /**
     * user is enabled?
     */
    @JsonIgnore
    @Override
    public boolean isEnabled() {
        return state != null && state != 1;
    }
}
